package com.tianhao.luo.utils;

import com.tianhao.luo.configure.WeChatConfig;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tianhao.luo
 * @date 2020/3/10 12:34
 */
@Component
public class WeChatUtils {



    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatUtils.class);
    @Autowired
    private WeChatConfig weChatConfig;

    public String checkLink(String signature,String timestamp,String nonce,String echostr){
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = {weChatConfig.getToken(),timestamp,nonce};
        Arrays.sort(arr);
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder stringBuilder = new StringBuilder();
        for (String s:arr) {
            stringBuilder.append(s);
        }
        String sha1 = getSha1(stringBuilder.toString());
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(sha1)) {
            return echostr;
        }else {
            return "";
        }
    }


    private  String getSha1(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    public Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        InputStream is = request.getInputStream();
        Document doc = reader.read(is);
        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        is.close();
        return map;
    }

    public String mapToXml(Map<String, String> map) throws IOException, DocumentException {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        for (String key : map.keySet()) {
            String value = "<![CDATA[" + map.get(key) + "]]>";
            if ("MediaId".equals(key)) {
                switch (map.get("MsgType")) {
                    case "image":
                        sb.append("<Image><" + key + ">" + value + "</" + key + "></Image>");
                        break;
                    case "voice":
                        sb.append("<Voice><" + key + ">" + value + "</" + key + "></Voice>");
                        break;
                    default:
                        break;
                }
            } else {
                sb.append("<" + key + ">" + value + "</" + key + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
